package com.ruoyi.develop.lnZhaobiao.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
        import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.DateUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.lnZhaobiao.mapper.LnZhaobiaoMapper;
import com.ruoyi.develop.lnZhaobiao.domain.LnZhaobiao;
import com.ruoyi.develop.lnZhaobiao.service.ILnZhaobiaoService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 招标信息Service业务层处理
 * @author lmm
 * @date 2025-07-30
 */
@Service
public class LnZhaobiaoServiceImpl implements ILnZhaobiaoService {
    @Resource
    private LnZhaobiaoMapper lnZhaobiaoMapper;
    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;

    /**
     * 查询招标信息
     * @param id 招标信息主键
     * @return 招标信息
     */
    @Override
    public LnZhaobiao selectById(String id) {
        return lnZhaobiaoMapper.selectById(id);
    }

    /**
     * 查询招标信息列表
     * @param entity 招标信息
     * @return 招标信息
     */
    @Override
    public List<LnZhaobiao> selectList(LnZhaobiao entity) {
        return lnZhaobiaoMapper.selectList(entity);
    }

    @Override
    public List<LnZhaobiao> selectListZb(LnZhaobiao entity) {
        return lnZhaobiaoMapper.selectListZb(entity);
    }
    /**
     * 新增招标信息
     * @param entity 招标信息
     * @return 结果
     */
    @Override
    public int insert(LnZhaobiao entity) {
        if(StringUtils.isBlank(entity.getId())){
            entity.setId(IdUtils.fastSimpleUUID());
        }
                entity.setCreateBy(SecurityUtils.getUsername());
                entity.setCreateTime(DateUtils.getNowDate());
            return lnZhaobiaoMapper.insert(entity);
    }

    /**
     * 修改招标信息
     * @param entity 招标信息
     * @return 结果
     */
    @Override
    public int update(LnZhaobiao entity) {
                entity.setUpdateBy(SecurityUtils.getUsername());
                entity.setUpdateTime(DateUtils.getNowDate());
        return lnZhaobiaoMapper.update(entity);
    }

    /**
     * 批量删除招标信息
     * @param ids 需要删除的招标信息主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return lnZhaobiaoMapper.deleteByIds(ids);
    }

    /**
     * 删除招标信息信息
     * @param id 招标信息主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return lnZhaobiaoMapper.deleteById(id);
    }
    public LnZhaobiao selectByName(String name) {
        return lnZhaobiaoMapper.selectByName(name);
    }

    @Override
    public Map<String, Object> importData(LnZhaobiao lnZhaobiao, MultipartFile file) {
        String tmplName = "zhaobiao.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        int i = 0;
        int j = 0;
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<LnZhaobiao> list = new ArrayList<>();
            List<LnZhaobiao> listToDo = new ArrayList<>();
            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (int k = 0; k < list.size(); k++) {
                    LnZhaobiao entity = new LnZhaobiao();
                    entity.setId(IdUtils.fastSimpleUUID());
                    LnZhaobiao info = list.get(k);
                    BeanUtils.copyProperties(info, entity, "id");
                    if (StringUtils.isNotBlank(info.getIdx())){
                        try {
                            if(StringUtils.isNotBlank(info.getOpenDateStr())){
                                boolean arriveTimeMatch = Pattern.matches("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}", info.getOpenDateStr());
                                if (!arriveTimeMatch) {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
                                    entity.setOpenDate(df.parse(info.getOpenDateStr()));
                                } else {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
                                    String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getOpenDateStr())));
                                    entity.setOpenDate(DateUtils.parseDate(date, "yyyy-MM-dd HH:mm:dd"));
                                }
                            }
                        } catch (Exception e) {
                            errortext += "行号为 " + info.getIdx() + "行的数据，开标日期时间格式错误，请修改后再上传！";
                            break;
                        }

                        try {
                            if(StringUtils.isNotBlank(info.getWinMoneyStr())){
                                String orderCountStr = info.getWinMoneyStr().replace("\n", "").replace("\r", "");
                                info.setWinMoneyStr(orderCountStr);
                                entity.setWinMoney(new BigDecimal(info.getWinMoneyStr()));
                            }
                        } catch (Exception e) {
                            errortext += "行号为 " + info.getIdx() + "行的数据，中标金额格式错误，请修改后再上传！";
                            break;
                        }
                        try {
                            if(StringUtils.isNotBlank(info.getWinDateStr())){
                                boolean arriveTimeMatch = Pattern.matches("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}", info.getWinDateStr());
                                if (!arriveTimeMatch) {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
                                    entity.setWinDate(df.parse(info.getWinDateStr()));
                                } else {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
                                    String date = df.format(DateUtil.getJavaDate(Double.parseDouble(info.getWinDateStr())));
                                    entity.setWinDate(DateUtils.parseDate(date, "yyyy-MM-dd HH:mm:dd"));
                                }
                            }
                        } catch (Exception e) {
                            errortext += "行号为 " + info.getIdx() + "行的数据，中标日期时间格式错误，请修改后再上传！";
                            break;
                        }
                        try {
                            if(StringUtils.isNotBlank(info.getWinServiceStr())){
                                String orderCountStr = info.getWinServiceStr().replace("\n", "").replace("\r", "");
                                info.setWinServiceStr(orderCountStr);
                                entity.setWinService(new BigDecimal(info.getWinServiceStr()));
                            }
                        } catch (Exception e) {
                            errortext += "行号为 " + info.getIdx() + "行的数据，中标服务费格式错误，请修改后再上传！";
                            break;
                        }
                    } else {
                        map.put("num", "第" + k + "行数据，序号不能为空");
                        return map;
                    }


                    if (StringUtils.isNotBlank(errortext)) {
                        map.put("errorText", errortext);
                        map.put("num", i);
                        map.put("numupdate", j);
                        return map;
                    } else {
                        listToDo.add(entity);
                    }
                }
            }
            if (StringUtils.isBlank(errortext)) {
                for (LnZhaobiao info : listToDo) {
                    LnZhaobiao lnZhaobiao1=lnZhaobiaoMapper.selectByName(info.getName());
                    if(lnZhaobiao1!=null){
                        BeanUtils.copyProperties(info, lnZhaobiao1, "id");
                        update(lnZhaobiao1);
                    }else{
                        insert(info);
                    }
                }
                i=listToDo.size();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", i);
        map.put("numupdate", j);
        return map;
    }
}
